package org.jet.emall.security.handler;

import com.alibaba.fastjson.JSON;
import org.jet.emall.common.restful.result.CommonResult;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 匿名用户访问无权限资源时的错误回调,因为在此返回401
 * @author xiaozai
 * @version 1.0
 * @date 2020-04-09 12:09
 */
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        authException.printStackTrace();
        CommonResult<Object> result = CommonResult.unauthorized();
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(JSON.toJSONString(result));
        response.flushBuffer();
    }
}
